/*
 * Copyright 2010, 2011 Matt Oliveri
 *
 * This file is part of JConfigGen
 *
 * JConfigGen is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JConfigGen is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JConfigGen.  If not, see <http://www.gnu.org/licenses/>.
 */

package atma.jconfiggen.sax;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import atma.jconfiggen.Expr;
import atma.jconfiggen.NewObj;
import atma.jconfiggen.PxRef;
import atma.jconfiggen.Call;

class NewH extends ExpListH
{
	final ArrayList<Expr> pnt;
	NewObj newo;

	NewH(SAXHandler s,ArrayList<Expr> p) {super(s);pnt = p;}

	final void setupSub()
	{
		sub = new ArrayList<Expr>(10);
		setupWith(pnt,newo);
	}

	final void addSetter(String nm,String val)
	{
		StringBuilder nm2 = new StringBuilder(nm.length() + 3);
		nm2.append("set");
		nm2.append(Character.toUpperCase(nm.charAt(0)));
		nm2.append(nm.substring(1));
		sub.add(new Call(saxh.config,saxh.loc.getLineNumber(),null,null,new PxRef(saxh.withs.peek()),nm2.toString(),val));
	}

	final NewH init(NewObj o,int extc,int[] extv,Attributes attr)
	{
		newo = o;
		if (extc > 0)
		{
			setupSub();
			for (int i = 0;i < extc;++i)
			{
				int j = extv[i];
				addSetter(attr.getLocalName(j),attr.getValue(j));
			}
		}
		return this;
	}

	final ElemH elemexp(SAXHandler.Elem e,Attributes attr) throws SAXException {return super.elem(e,attr);}

	ElemH elem(SAXHandler.Elem e,Attributes attr) throws SAXException
	{
		if (e == SAXHandler.Elem.CONSTRUCTOR) complain("A constructor element is only allowed if the args attribute is not set.");
		if (sub == null) setupSub();
		return elemexp(e,attr);
	}

	ElemH elemstr(String tag,Attributes attr) throws SAXException
	{
		if (sub == null) setupSub();
		return scall(tag,attr);
	}

	final void addPxRef() {sub.add(new PxRef(saxh.withs.pop()));}

	void end()
	{
		if (sub == null) pnt.add(newo);
		else addPxRef();
	}
}
